package com.wangcang.widgetlibrary.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.bean.SelectBean;

import java.util.List;

/**
 * 单选列表 Adapter
 * Created by ShineF on 2017/7/12 0012.
 */

public class CheckBoxListAdapter extends BaseAdapter {

    private Context mContext;
    private List<SelectBean> mList;
    ViewHolder mHolder;
    private int mSelectorPos = -1;
    private ItemClick mListener;

    public CheckBoxListAdapter(Context context, List<SelectBean> list) {
        this.mContext = context;
        this.mList = list;
    }

    public void setOnItemListener(ItemClick listener){
        this.mListener = listener;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.view_list_checkbox_item_layout, null);
            mHolder = new ViewHolder(convertView);
            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }
        final SelectBean selectBean = mList.get(position);
        if (selectBean.isSelected) {
            mHolder.mTvDescription.setSelected(true);
            mHolder.mIvSelect.setVisibility(View.VISIBLE);
        } else {
            mHolder.mTvDescription.setSelected(false);
            mHolder.mIvSelect.setVisibility(View.GONE);
        }
        mHolder.mTvDescription.setText(selectBean.text);
        mHolder.mRlItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 selectBean.isSelected = !selectBean.isSelected;
                if(mListener != null){
                    mListener.onItemClickListener(position, selectBean);
                }
                notifyDataSetChanged();
            }
        });
        return convertView;
    }

    public interface ItemClick{
        void onItemClickListener(int position, SelectBean bean);
    }

    class ViewHolder {

        RelativeLayout mRlItem;
        TextView mTvDescription;
        ImageView mIvSelect;

        public ViewHolder(View view) {
            mRlItem = (RelativeLayout) view.findViewById(R.id.rl_item);
            mTvDescription = (TextView) view.findViewById(R.id.tv_description);
            mIvSelect = (ImageView) view.findViewById(R.id.iv_select);
        }
    }
}
